<template>
  <div class="login-model">
    <div class="mask" @click="hideLogin"></div>

    <div class="login-box">
      <img class="close" @click="hideLogin" src="../assets/img/close.png" />
      <ul class="title">
        <li :class="isShowForm ? 'active' : ''" @click="isShowForm = true">
          手机号码登陆
        </li>
        <li style="margin: -2px 10px 0; cursor: none">|</li>
        <li :class="isShowForm ? '' : 'active'" @click="toShowWeiXin">
          微信扫码登陆
        </li>
      </ul>
      <div class="body">
        <div class="form" v-show="isShowForm">
          <div class="input-group">
            <input type="text" placeholder="请输入手机号" v-model="phoneNum" />
          </div>

          <div class="cover mb10">
            <hua-kuai @verify="verify" @refresh="refresh"></hua-kuai>
          </div>

          <div class="input-group code mb10">
            <input type="text" placeholder="请输入短信验证码" v-model="SMScode"/>
            <div class="btn" :class="isShowCount ? 'has-count' : ''">
              <span v-show="!isShowCount" @click="getSMSCode">获取验证码</span
              ><span v-show="isShowCount">{{ count }}s</span>
            </div>
          </div>

          <div class="btn" @click="submitLogin">登录</div>
        </div>

        <div class="wx-qrcode" id="weixin" v-show="!isShowForm">二维码</div>
      </div>
    </div>
  </div>
</template>










<script>
import { SendSMSAPI } from "@/request/api";
import { PhoneLoginAPI,WeixinBindingApi,getUserInfoApi} from "@/request/api";
import { validatePhoneNumber } from "@/utils";
import { mapMutations ,mapActions} from "vuex";

export default {
  components: {},
  data() {
    return {
      isShowForm: true,
      isValidCaptach: false,
      phoneNum: "",
      isShowCount: false,
      count: 60,
      SMScode:""
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showLoginModal/changeIsShowLoginModal",
      changeIsLogin:"loginStatus/changeIsLogin"
    }),

    ...mapActions({
         asyncchangeIsShowToastModal:"showToast/asyncchangeIsShowToastModal",
         ayncChangeUserInfo:"userInfo/ayncChangeUserInfo"
    }),
    hideLogin() {
      this.changeIsShowLoginModal(false);
    },
    verify(result) {
      this.isValidCaptach = result;
      console.log(result); // result为true表示验证通过，false表示验证三次都失败了哦
    },
    refresh() {
      this.isValidCaptach = false;
      console.log("用户点击了初始化");
    },
    countDown() {
      //倒计时定时器
      let timer = setInterval(() => {
        this.count--;
        if (this.count === 0) {
          this.isShowCount = false;
          this.count = 60;
          //关闭定时器
          clearInterval(timer);
        }
      }, 1000);
    },

    verifyFn() {
      //1.验证手机号格式是否正确 + 滑块验证码
      if (!validatePhoneNumber(this.phoneNum)) {
       this.asyncchangeIsShowToastModal({
            msg: "请输入正确的手机号码!",
            type : "danger"
        })

        //给用户直接聚焦
        this.$refs.phoneNum.focus();
        return false;
      }
      if (!this.isValidCaptach) {
       this.asyncchangeIsShowToastModal({
            msg: "请将滑块验证到正确位置!",
            type : "danger"
        })
        return false;
      }
      return true;
    },

    async getSMSCode() {
      if (!this.verifyFn()) {
        return;
      }
      //暂时不判断res请求值
      //let res = await SendSMSAPI({phone:this.phoneNum.trim()});
      // if(res.code == 0){
     this.asyncchangeIsShowToastModal({
            msg: "验证码发送成功，请注意查收!",
            type : "success"
      })

      this.isShowCount = true;
      //短信验证码倒计时
      this.countDown();
    },
    async submitLogin() {

      if(!this.verifyFn()){
         return;
      }
     

    if(!this.SMScode.trim()){      
       this.asyncchangeIsShowToastModal({
            msg: "请输入验证码!",
            type : "success"
      })
      return;
    }

     
    let uuid = localStorage.getItem("uuid")

    let res = null;
    if(uuid){
      res = await  WeixinBindingApi({
             phone:this.phoneNum.trim(),
             verifyCode:this.SMScode.trim(),
             uuid : uuid
       })
    }else{
         //mock登录
         res =  await PhoneLoginAPI({
          phone:this.phoneNum.trim(),
          verifyCode:this.SMScode.trim()
        })
    }


    if(res){
  
          this.asyncchangeIsShowToastModal({
              msg: "登陆成功!",
              type : "success"

          })
          
          this.hideLogin();
          //保存token到本地
          localStorage.setItem("x-auth-token","12345678");
          //切换登陆的切换值
          this.changeIsLogin(true);

          if(uuid){
            //删除uuid并且清除浏览器地址栏上的code
              localStorage.removeItem("uuid");
              this.$router.push(this.$route.path)
           }


          console.log("发送用户i请求数据")
          this.ayncChangeUserInfo();
          
    }
  
    },


    toShowWeiXin(){
      this.isShowForm = false;
      //获取二维码
      let _this = this;
      new WxLogin({
            id: "weixin",
            appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
            scope: "snsapi_login",
            // 扫码成功后重定向的接⼝
            redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
            // state填写编码后的url
            state: encodeURIComponent(window.btoa("http://127.0.0.1:8080" +_this.$route.path)),
            // 调⽤样式⽂件
            href: "data:text/css;base64,Lyogd3hsb2dpbi5jc3MgKi8NCi5pbXBvd2VyQm94IC50aXRsZSwgLmltcG93ZXJCb3ggLmluZm97DQogIGRpc3BsYXk6IG5vbmU7DQp9DQoNCi5pbXBvd2VyQm94IC5xcmNvZGV7DQogIG1hcmdpbi10b3A6IDIwcHg7DQp9",
        });
    },
   



  },
};
</script>

<style lang="less" scoped>
@import "../assets/css/global.less";

.login-model {
  width: 100%;
  height: 100%;
  position: fixed;
  background-color: rgba(0, 0, 0, 0.5);
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .login-box {
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    margin: auto;

    .close {
      position: absolute;
      right: 60px;
      top: 15px;
      cursor: pointer;
    }

    .title {
      display: flex;
      justify-content: center;
      padding: 20px 0 15px;
      color: #ccc;
      font-size: 16px;

      li {
        cursor: pointer;
      }

      .active {
        color: #333;
      }
    }

    .body {
      width: 360px;
      height: 200px;
      margin: 0 auto;

      .form {
        .input-group {
          display: flex;
          input {
            height: 40px;
            width: 100%;
            text-indent: 10px;
            margin-bottom: 5px;
            border: 1px solid #ccc;
          }
        }

        .code input {
          width: 240px;
          margin-right: 8px;
        }
        .code .btn {
          flex: 1;
          height: 40px;
        }

        .btn {
          height: 40px;
          line-height: 50px;
          background-color: @base-color;
          color: #fff;
          text-align: center;
          cursor: pointer;
        }

        .has-count {
          background-color: #ccc;
        }
      }
    }
  }
}


.wx-qrcode{
  margin-top: -20px;
  display: flex;
  justify-content: center;
}
</style>